package com.core.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.common.constants.CaptchaConstant;
import com.common.enums.ErrorCode;
import com.common.model.dto.user.UserLoginDTO;
import com.common.model.dto.user.UserRegisterDTO;
import com.common.model.vo.SysUserVO;
import com.common.response.BaseResponse;
import com.common.response.ResultUtils;
import com.core.service.SysUserService;
import com.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author : 帅宏-coding
 * @version : 1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
  @Resource private SysUserService sysUserService;

  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public BaseResponse userRegister(@RequestBody UserRegisterDTO userRegisterDTO) {
    if (StringUtils.isAnyBlank(userRegisterDTO.getUserName(), userRegisterDTO.getUserPassword())) {
      return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
    }
    String userName = userRegisterDTO.getUserName().trim();
    String userPassword = userRegisterDTO.getUserPassword().trim();
    String confirmPassword = userRegisterDTO.getConfirmPassword().trim();
    long flag = sysUserService.userRegister(userName, userPassword, confirmPassword);
    if (flag <= 0) {
      return ResultUtils.error(ErrorCode.PARAMS_ERROR, "注册失败");
    }
    return ResultUtils.success(userName + "注册成功！欢迎新成员加入~~~");
  }


  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public BaseResponse<SysUserVO> userLoginWithGet(
          UserLoginDTO userLoginDTO, HttpServletRequest request) {

    /** 先对验证码进行验证 */
    try {
      String random =
              (String) request.getSession().getAttribute(CaptchaConstant.CAPTCHA_KEY);
      if (StringUtils.isBlank(userLoginDTO.getCaptcha().trim())) {
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请输入验证码");
      }
      if (!random.equalsIgnoreCase(userLoginDTO.getCaptcha().trim())) {
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, "验证码错误，请重新输入");
      }
    } catch (Exception e) {
      log.error("验证码校验失败", e);
      return ResultUtils.error(ErrorCode.PARAMS_ERROR, "验证码校验失败，可能的原因（1.验证码过期，请重新获取 2.验证码错误，请重新输入）");
    }

    /** 验证码验证通过，开始验证登录账号和密码 */
    String userName = userLoginDTO.getUserName().trim();
    String userPassword = userLoginDTO.getUserPassword().trim();
    Integer isRememberMe = userLoginDTO.getIsRememberMe();

    // 账号和密码的参数校验
    if (StringUtils.isAnyBlank(userName, userPassword)) {
      return ResultUtils.error(ErrorCode.PARAMS_ERROR, "登录账号或密码不能为空");
    }
    // 执行登录的业务Service
    SysUserVO sysUserVO = sysUserService.userLogin(userName, userPassword,isRememberMe, request);
    // 验证码 + 账号 + 密码 都验证成功 则返回 jwt 令牌
    return ResultUtils.success(sysUserVO);
  }

  @RequestMapping(value = "/logout", method = RequestMethod.GET)
  public BaseResponse userLogout(HttpServletRequest request) {
    String token = request.getHeader(JwtUtils.TOKEN_HEADER);
    String userName = JwtUtils.getUserNameByToken(token);
    boolean logoutFlag = sysUserService.userLogout(userName);
    if (logoutFlag) {
      return ResultUtils.success("退出成功！");
    }
    return ResultUtils.error(ErrorCode.OPERATION_ERROR, "退出失败，请联系开发人员");
  }

  @RequestMapping(value = "/getCurrentLoginUser", method = RequestMethod.GET)
  public BaseResponse<SysUserVO> getCurrentLoginUser(HttpServletRequest request) {
    SysUserVO currentLoginUser = sysUserService.getCurrentLoginUser(request);
    return ResultUtils.success(currentLoginUser);
  }

  /** 生成验证码 */
  @RequestMapping(value = "/getVerifyCode", method = RequestMethod.GET)
  public void getVerify(HttpServletRequest request, HttpServletResponse response) throws IOException {

//    // 从session中获取随机数，并设置 key："RANDOM_CODE_KEY" value：验证码
//    try {
//      response.setContentType("image/jpeg"); // 设置相应类型,告诉浏览器输出的内容为图片
//      response.setHeader("Pragma", "No-cache"); // 设置响应头信息，告诉浏览器不要缓存此内容
//      response.setHeader("Cache-Control", "no-cache");
//      response.setDateHeader("Expire", 0);
//      RandomValidateCodeUtils randomValidateCode = new RandomValidateCodeUtils();
//      // 设置 key："RANDOM_CODE_KEY" value：验证码
//      randomValidateCode.getRandCodeImage(request, response); // 输出验证码图片方法
//    } catch (Exception e) {
//      log.error("获取验证码失败>>>> ", e);
//    }

    // 自定义纯数字的验证码（随机4位数字，可重复）
    RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
    CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100,4, 20);
    circleCaptcha.setGenerator(randomGenerator);
    // 重新生成code
    circleCaptcha.createCode();

    // 设置响应类型为 PNG
    response.setContentType("image/png");
    // 禁止缓存
    response.setHeader("Cache-Control", "no-store, no-cache");
    //图形验证码写出，可以写出到文件，也可以写出到流
    circleCaptcha.write(response.getOutputStream());
    //获取验证码中的文字内容
    String verifyCode = circleCaptcha.getCode();
    log.info("生成验证码：{}",verifyCode);
    request.getSession().setAttribute(CaptchaConstant.CAPTCHA_KEY,verifyCode);

//    //定义图形验证码的长、宽、验证码字符数、干扰元素个数
//    CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
//    // 设置响应类型为 PNG
//    response.setContentType("image/png");
//    // 禁止缓存
//    response.setHeader("Cache-Control", "no-store, no-cache");
//    //图形验证码写出，可以写出到文件，也可以写出到流
//      captcha.write(response.getOutputStream());
//    //获取验证码中的文字内容
//    String verifyCode = captcha.getCode();
//    log.info("验证码：{}",verifyCode);
//    request.getSession().setAttribute(CaptchaConstant.CAPTCHA_KEY,verifyCode);

//    //定义图形验证码的长和宽
//    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
//    //图形验证码写出，可以写出到文件，也可以写出到流
//      lineCaptcha.write(response.getOutputStream());
//      //获取验证码中的文字内容
//      String verifyCode = lineCaptcha.getCode();
//      request.getSession().setAttribute(CaptchaConstant.CAPTCHA_KEY,verifyCode);
  }

  @RequestMapping(value = "/authcPage", method = RequestMethod.GET)
  public BaseResponse<String> authcPage() {
    return ResultUtils.success("该界面是需要登录认证的");
  }
  @RequestMapping(value = "/rememberMe", method = RequestMethod.GET)
  public BaseResponse<String> rememberMe(HttpServletRequest request) {
    return ResultUtils.success("记住我生效！！！");
  }
}
